package com.lzx.iteam;


import android.app.*;
import android.content.*;
import android.net.Uri;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.lzx.iteam.R;
import com.lzx.iteam.contactssearch.ContactsDBReader;
import com.lzx.iteam.widget.PersonVO;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class BatchSendSmsService extends Service{

    public static final String SENT_SMS_ACTION = "SENT_SMS_ACTION";
    public static  int SEND_SMS_ID = R.drawable.team_icon;
    private BroadcastReceiver sendSuccessRecv;
    private SmsManager smsManager;
    private ArrayList<String> msgs;
    private int currentPerson = 0;
    private int currentMsg = 0;
    private ArrayList<PendingIntent> sendIntents = new ArrayList<PendingIntent>();
    private AtomicInteger successNum;
    private AtomicInteger failNum;
    private ArrayList<PersonVO> persons = new ArrayList<PersonVO>();
    public static volatile boolean running;
    private NotificationManager notificationMgr;
    
    private ArrayList<Intent> blockIntents = new ArrayList<Intent>();
    @Override
    public void onCreate() {
        super.onCreate();
        sendSuccessRecv = new SmsSendSuccessReceiver();
        registerReceiver(sendSuccessRecv,new IntentFilter(SENT_SMS_ACTION) );
        smsManager = SmsManager.getDefault();
        notificationMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent==null){
            return START_NOT_STICKY;
        }
        if(!running){
            running = true;
            String content = intent.getStringExtra("content");
            persons = intent.getParcelableArrayListExtra("persons");
            successNum = new AtomicInteger(0);
            failNum = new AtomicInteger(0);
            msgs = smsManager.divideMessage(content);
            currentMsg = 0;
            currentPerson = 0;
            Intent intent1 = new Intent(SENT_SMS_ACTION);
            PendingIntent sendIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,intent1 , 0);
            for(int i=0;i<msgs.size();i++){
                sendIntents.add(sendIntent);
            }
            Notification notify = createStartNotification();
            notificationMgr.notify(SEND_SMS_ID, notify);
            smsManager.sendMultipartTextMessage(persons.get(currentPerson).number, null, msgs, sendIntents, null);
        }else{
            blockIntents.add(intent);
            Toast.makeText(getApplicationContext(), "已加入发送队列,请稍候...", Toast.LENGTH_LONG).show();
        }
        
        
        return START_NOT_STICKY;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        running = false;
        unregisterReceiver(sendSuccessRecv);
    }
    
    class SmsSendSuccessReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if(!running){
                Notification notify = createCancelNotification();
                notificationMgr.notify(SEND_SMS_ID, notify);
                if(blockIntents.size()==0){
                    stopSelf();
                }else{
                    SEND_SMS_ID+=1;
                    Intent intent2 = blockIntents.remove(0);
                    onStartCommand(intent2, 0, 0);
                }
                
                return;
            }
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        successNum.addAndGet(1);
                        ContentValues values = new ContentValues();
                        values.put("address", persons.get(currentPerson).number);
                        values.put("body", msgs.get(currentMsg));
                        values.put("date", System.currentTimeMillis());
                        getContentResolver().insert(Uri.parse("content://sms/sent"), values);
                    break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        failNum.addAndGet(1);
                        values = new ContentValues();
                        values.put("address", persons.get(currentPerson).number);
                        values.put("body", msgs.get(currentMsg));
                        values.put("date", System.currentTimeMillis());
                        getContentResolver().insert(Uri.parse("content://sms/failed"), values);
                        
                    break;
                }
                currentMsg++;
                if(currentMsg==msgs.size()){
                    currentMsg=0;
                    String firstName = ContactsDBReader.getContactNameByContactId(getContentResolver(), persons.get(currentPerson).id);
                    Notification notify = createProcessNotification(firstName+"发送完毕", currentPerson);
                    notificationMgr.notify(SEND_SMS_ID, notify);
                    currentPerson++;
                    if(currentPerson!=persons.size()){
                        smsManager.sendMultipartTextMessage(persons.get(currentPerson).number, null, msgs, sendIntents, null);
                    }else{
                        if(blockIntents.size()==0){
                            notify = createFinishNotification();
                            notificationMgr.notify(SEND_SMS_ID, notify);
                            stopSelf();
                            running = false;
                        }else{
                            notify = createFinishNotification();
                            notificationMgr.notify(SEND_SMS_ID, notify);
                            SEND_SMS_ID+=1;
                            running = false;
                            Intent intent2 = blockIntents.remove(0);
                            onStartCommand(intent2, 0, 0);
                        }
                       
                    }
                }
        }
        
    }
    
    public Notification createProcessNotification(String tickerText,int currentCount){
        currentCount+=1;
        Notification notification = new Notification();
        notification.icon = R.drawable.team_icon;
        notification.flags = Notification.FLAG_ONGOING_EVENT;
        notification.tickerText = tickerText;
        notification.when = System.currentTimeMillis();
        Intent intent = new Intent(this,CancelBatchSendSmsActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        notification.contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
        RemoteViews rv = new RemoteViews(getPackageName(), R.layout.notify_view);
        notification.contentView = rv;
        rv.setProgressBar(R.id.progress, persons.size(), currentCount, false);
        rv.setTextViewText(R.id.progress_tv, String.valueOf(currentCount * 100 / persons.size())+"%");
        return notification;
    }
    
    public Notification createStartNotification(){
        String title = "群发短信开始...";
        Notification notification = new Notification();
        notification.icon = R.drawable.team_icon;
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.tickerText = title;
        notification.setLatestEventInfo(this, title, title, PendingIntent.getActivity(this, 0,  new Intent(), 0));
        return notification;
    }
    
    public Notification createFinishNotification(){
        String title = "群发短信完毕,成功:"+successNum+"条,失败:"+failNum+"条";
        Notification notification = new Notification();
        notification.icon = R.drawable.team_icon;
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.tickerText = title;
        notification.setLatestEventInfo(this, title, title, PendingIntent.getActivity(this, 0,  new Intent(), 0));
        return notification;
    }
    
    public Notification createCancelNotification(){
        String title = "群发短信已取消";
        Notification notification = new Notification();
        notification.icon = R.drawable.team_icon;
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.tickerText = title;
        notification.setLatestEventInfo(this, title, title, PendingIntent.getActivity(this, 0,  new Intent(), 0));
        return notification;
    }
    

}
